<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "tag".
 *
 * @property integer $id
 * @property string $name
 * @property integer $frequency
 */
class Tag extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tag';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['frequency'], 'integer'],
            [['name'], 'string', 'max' => 128],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'frequency' => 'Frequency',
        ];
    }
    /*
     * *正则表达式分割字符串
     */
   
    public static function string2array($tags){
    	return preg_split('/\s*,\s*/',trim($tags),-1,PREG_SPLIT_NO_EMPTY);//preg_ split() 函数用于正则表达式分割   字符串。
    	//PREG_SPLIT_NO_EMPTY：preg_split() 只返回非空的成分
    
    }
    /*
     
     * 把数组元素组合成字符串
     * */
   
    public static function array2string($tags){
    	return implode(',',$tags);
    	
    }
    /*
     * 添加标签
     */
    public static function addTags($tags){
    	
    	if(empty($tags)) return;
    	foreach($tags as $name){
    		$aTag=Tag::find()->where(['name'=>$name])->one();
    		$aTagCount=Tag::find()->where(['name'=>$name])->count();
    		
    		if(!$aTagCount){//如果标签不存在
    			$tag=new Tag;
    			$tag->name=$name;
    			$tag->frequency=1;
    			$tag->save();//保存数据
    		}else{
    			$aTag->frequency+=1;
    			$aTag->save();
    		}
    		
    	}
    }
    /*多看多看多看
     * 
     * 删除标签
     */
    public static function removeTags($tags){
    	if(empty($tags)) return ;
    	foreach($tags as $name){
    		$aTag=Tag::find()->where(['name'=>$name])->one();
<<<<<<< HEAD
    		$aTagCount=Tag::find()->where(['name'=>$name])->count();
=======
    		$aTagCount=Tag::find()->wher(['name'=>$name])->count();
>>>>>>> 028a9e1ed35c5e94b64c6b6feb0151fb63c3eadc
    		if($aTagCount){
    			if($aTagCount && $aTag->frequency<=1){//注意这个条件容易忽略
    				$aTag->delete();
    			}else{
    				$aTag->frequency-=1;
    				$aTag->save();
    				
    			}
    		}

    	}
    }
    public static function updateFrequency($oldTags,$newTags){
    	if(!empty($oldTags) || !empty($newTags)){
    		$oldTagsArray=self::string2array($oldTags);
    		$newTagsArray=self::string2array($newTags);
    		self::addTags(array_values(array_diff($newTagsArray,$oldTagsArray)));
    		self::removeTags(array_values(array_diff($oldTagsArray,$newTagsArray)));
    	}
    }
}
